package spt.slides;

import java.util.List;
import java.util.logging.Logger;

import spt.exceptions.PersistanceException;
import spt.exceptions.SlideException;
import spt.exceptions.ValidationException;

public class SlideManager {
	private final Logger log = Logger.getLogger(SlideManager.class.getName());
	
	private SlideDAO slideDao;
	
	public SlideManager(){
		slideDao = new SlideDAO();
	}
	
	public Slide getSlide(int id) throws SlideException{ 
		Slide slide = null;
		try {
			slide = slideDao.get(id);
		} catch (PersistanceException e) {
			throw new SlideException("Connection error.");
		}
		if(slide == null)
			throw new SlideException("There is no slide with id = " + id + ".");
		return slide;
	}
	
	
	public int addSlide(Slide slide) throws SlideException, ValidationException{
		try {
			return slideDao.save(slide);
		} catch (PersistanceException e) {
			log.severe(e.getMessage());
			throw new SlideException(e.getMessage());
		} catch (ValidationException e) {
			throw e;
		}
	}
	
	public void updateSlide(Slide slide) throws SlideException, ValidationException{
		if(!slideExists(slide.getId()))
			throw new SlideException("Could not update slide because that slide does not exist.");
		try {
			slideDao.update(slide);
		} catch (PersistanceException e) {
			log.severe(e.getMessage());
			throw new SlideException(e.getMessage());
		} catch (ValidationException e) {
			throw e;
		}
		log.info("Slide with id = " + slide.getId() + " was updated.");
	}
	
	public void deleteSlide(int id) throws SlideException{
		if(!slideExists(id))
			throw new SlideException("There is no slide with id = " + id + ".");
		try {
			slideDao.delete(id);
		} catch (PersistanceException e) {
			throw new SlideException(e.getMessage());
		}
		log.info("Slide with id = " + id + " was deleted.");
	}
	
	public boolean slideExists(int id) throws SlideException{
		Slide slide = null;
		try {
			slide = slideDao.get(id);
		} catch (PersistanceException e) {
			throw new SlideException(e.getMessage());
		}
		
		return (slide == null) ? false : true;
	}
	
	public List<Slide> getCurrentSlides() throws SlideException{
		try{
			return slideDao.getCurrentSlides();
		}catch(PersistanceException e){
			throw new SlideException(e.getMessage());
		}
	}
	
	public List<Integer> getSlidesIds() throws SlideException{
		try {
			return slideDao.getIds();
		} catch (PersistanceException e) {
			throw new SlideException("Connection error.");
		}
	}
}
